package com.wowangz.cms.syscore.autotask.job;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;

import com.wowangz.cms.common.utils.DataFormat;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.dailyoperation.store.pojo.StoreEntity;
import com.wowangz.cms.dailyoperation.store.service.StoreService;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.autotask.pojo.StoreLoginUser;
import com.wowangz.cms.syscore.autotask.service.StoreDatabaseResourceService;
import com.wowangz.cms.syscore.autotask.service.StoreLoginUserSyncService;
import com.wowangz.cms.syscore.pojo.RouteInfo;
import com.wowangz.cms.syscore.utils.DataPageUtil;
import com.wowangz.cms.syscore.utils.JedisUtil;

public class StoreLoginUserSync extends BaseJob {

	/**
	 * 同步商户所有可登录用户
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void innerExecute(JobExecutionContext context) throws Exception {
		// 商户管理员用户同步
		StoreLoginUser storeLoginUser = new StoreLoginUser();
		storeLoginUser.setStatusid(SysConstant.RecordStatus.VALID);
		storeLoginUser.setUsertype(SysConstant.StoreUserType.ADMIN);
		Map map = new HashMap();
		StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, false);
		StoreLoginUserSyncService storeLoginUserSynchronizationService = (StoreLoginUserSyncService) IssTransactionContainer
				.getInstance(StoreLoginUserSyncService.class, false);
		long admin_count = storeLoginUserSynchronizationService.queryLoginAdminUserCount(storeLoginUser);
		int admin_page = DataPageUtil.totalPages(Long.valueOf(admin_count).intValue());
		for (int i = 1; i < admin_page + 1; i++) {
			int pageStartRow = DataPageUtil.pageNum * (i - 1);
			int pageEndRow = DataPageUtil.pageNum;
			storeLoginUser.setStartrow(Long.valueOf(pageStartRow));
			storeLoginUser.setEndrow(Long.valueOf(pageEndRow));
			List<StoreLoginUser> list = storeLoginUserSynchronizationService.queryLoginAdminUser(storeLoginUser);
			for (StoreLoginUser user : list) {
				map.put("id", user.getStoreid());
				map.put("statusid", SysConstant.RecordStatus.VALID);
				StoreEntity storeEntity = storeService.queryStoreById(map);
				if (storeEntity != null) {
					user.setPhone(storeEntity.getTelephonenumber());
					user.setEmail(storeEntity.getEmail());
				}
				System.out.println("redis中的登陆用户：" + user.getLoginname());
				user.setCanLogin(SysConstant.YesOrNo.YES);
				user.setUsertype(SysConstant.StoreUserType.ADMIN);
				user.setUsername(user.getLoginname());
				JedisUtil.insertPublicDataObject(user.getLoginname(), user, JedisUtil.STORE_LOGINUSER);
			}
		}

		// 商户普通用户同步
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;

		Map query = new HashMap();
		query.put("state", SysConstant.CommonApproveStatus.OK);
		query.put("statusid", SysConstant.RecordStatus.VALID);
		StoreDatabaseResourceService storeDatabaseResourceService = (StoreDatabaseResourceService) IssTransactionContainer
				.getInstance(StoreDatabaseResourceService.class, false);
		long norl_count = storeDatabaseResourceService.queryStoreDatabaseResourceCount(query);
		int norl_page = DataPageUtil.totalPages(Long.valueOf(norl_count).intValue());
		for (int i = 1; i < norl_page + 1; i++) {
			int pageStartRow = DataPageUtil.pageNum * (i - 1);
			if (i != 1) {
				pageStartRow = DataPageUtil.pageNum * (i - 1) + 1;
			}
			int pageEndRow = DataPageUtil.pageNum * i;
			if (norl_count <= pageEndRow) {
				pageEndRow = Long.valueOf(norl_count).intValue();
			}
			query.put("startrow", pageStartRow);
			query.put("endrow", pageEndRow);
			List<RouteInfo> list = storeDatabaseResourceService.queryStoreDatabaseResource(query);
			for (RouteInfo routeInfo : list) {
				try {
					conn = getConnection(routeInfo);
					if (!conn.isClosed()) {
						String sql = "select id,storeid,loginname,username,validstart,validend,phone,email,"
								+ "pwdchangedate,checkstatus,statusid,password,alias from sys_user";
						st = conn.createStatement();
						rs = st.executeQuery(sql);
						while (rs.next()) {
							StoreLoginUser storeUser = new StoreLoginUser();
							storeUser.setId(rs.getLong("id"));
							storeUser.setStoreid(rs.getLong("storeid"));
							storeUser.setLoginname(rs.getString("loginname"));
							storeUser.setUsername(rs.getString("username"));
							storeUser.setPassword(rs.getString("password"));
							storeUser.setPhone(rs.getString("phone"));
							storeUser.setEmail(rs.getString("email"));
							String validstart = rs.getString("validstart");
							String validend = rs.getString("validend");
							String alias = rs.getString("alias");
							storeUser.setAlias(alias);
							java.util.Date parm_validstart = DataFormat.parseDate(validstart, DataFormat.DT_YYYY_MM_DD);
							java.util.Date parmvalidend = DataFormat.parseDate(validend, DataFormat.DT_YYYY_MM_DD);
							storeUser.setValidstart(parm_validstart);
							storeUser.setValidend(parmvalidend);
							String pwdchangedate = rs.getString("pwdchangedate");
							java.util.Date parm_pwdchangedate = DataFormat.parseDate(pwdchangedate,
									DataFormat.DT_YYYY_MM_DD);
							storeUser.setPwdchangedate(parm_pwdchangedate);
							if (rs.getLong("checkstatus") == SysConstant.CheckStatus.CHECKED) {
								storeUser.setCanLogin(SysConstant.YesOrNo.YES);
							} else {
								storeUser.setCanLogin(SysConstant.YesOrNo.NO);
							}
							storeUser.setUsertype(SysConstant.StoreUserType.NORMAL);
							JedisUtil.insertPublicDataObject(storeUser.getLoginname(), storeUser,
									JedisUtil.STORE_LOGINUSER);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					close(conn, null, st, rs);
					Thread.currentThread().sleep(10);
				}
			}
		}
	}

	/**
	 * 获得连接数据库对象Connection
	 * 
	 * @param routeInfo
	 * @return
	 * @throws SQLException
	 */
	public Connection getConnection(RouteInfo routeInfo) throws SQLException {

		Connection conn = null;
		String ip = routeInfo.getIp();
		String port = String.valueOf(routeInfo.getPort());
		String dbname = routeInfo.getDbname();
		String driver = "com.mysql.jdbc.Driver"; // 获取mysql数据库的驱动类
		String url = "jdbc:mysql://" + ip + ":" + port + "/" + dbname; // 连接数据库（kucun是数据库名）
		String name = routeInfo.getUsername();// 连接mysql的用户名
		String pwd = routeInfo.getPassword();// 连接mysql的密码
		try {
			Class.forName(driver);
			DriverManager.setLoginTimeout(5);
			conn = DriverManager.getConnection(url, name, pwd);// 获取连接对象
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 关闭jdbc连接对象
	 * 
	 * @param conn
	 * @param ps
	 * @param st
	 * @param rs
	 */
	public void close(Connection conn, PreparedStatement ps, Statement st, ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (st != null) {
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (ps != null) {
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
